/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */


package com.example.soscall.utils;

import static com.ecarx.xui.adaptapi.oncall.Call.CALL_STATUS_END;

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.ecarx.xui.adaptapi.oncall.Call;
import com.ecarx.xui.adaptapi.policy.IWindowManagerPolicy;
import com.ecarx.xui.adaptapi.policy.Policy;
import com.example.soscall.Constans;
import com.example.soscall.MyApplication;
import com.example.soscall.R;
import com.example.soscall.base.BaseCallView;
import com.example.soscall.view.RescueView;

import java.util.concurrent.TimeUnit;

import io.reactivex.disposables.Disposable;


public class WindowUtils {

    private static String TAG = "WindowUtils";

    private static WindowManager mWindowManager;
    private static WindowManager.LayoutParams mViewParams = null;
    public static ViewType mViewType = ViewType.NONE;
    private static RescueView mRescueView = null;           //ETA View
    private static View mArrivedView = null;                //ETA Arrived
    private static BaseCallView curCallView, normalCallView, miniCallView, littleCallView = null;
    private static View mAgreementView = null;           //Agreement View
    private static View mToastView = null;           //Toast View
    public enum ViewType {
        NONE,
        NORMAL,        //全屏
        MINISIZE,      //缩小化
        LITTLE         //极小化
    }

    /**
     * 根据当前ViewType显示ECall弹框，如果当前是缩小化或者极小画弹框则继续显示，反之则显示全屏Window
     */
    public static void showCallWindow(final int callType, final int callState) {

        if (mViewType == ViewType.MINISIZE || mViewType == ViewType.LITTLE) {
        } else {
        }
    }



    /**
     * 隐藏ECALl弹出框
     */
    public static void hideCallWindow() {

        if (null != curCallView) {
            try {
                curCallView.stopTime();
//                mCallView.stopTime();
                mWindowManager.removeView(curCallView);
//                mCallView = null;
                mViewType = ViewType.NONE;


            } catch (Exception e) {

            }
        }

    }


    private static WindowManager.LayoutParams initParam(Context context, int callType, boolean isFullScreen, boolean isRescue) {

        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        Policy policy = Policy.create(context);
        if (null != policy) {
            IWindowManagerPolicy imp = policy.getWindowManagerPolicy();
            int winType = imp.getWindowTypeByCode(callType == Call.CALL_TYPE_ECALL ? IWindowManagerPolicy.CODE_SOS : IWindowManagerPolicy.CODE_PHONE_POPUP);

            if (winType == -1 || winType == -7) {
                winType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            }
            params.type = winType;
            params.format = PixelFormat.RGBA_8888;

            if (isFullScreen) {
                params.width = WindowManager.LayoutParams.MATCH_PARENT;
                params.height = WindowManager.LayoutParams.MATCH_PARENT;
                params.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                        | WindowManager.LayoutParams.FLAG_FULLSCREEN;
            } else {
                // 如果是救援倒计时窗口，需要额外处理宽度和离顶部距离
                if (isRescue) {

                    params.y = 0;
                    params.width = Constans.rescue_width;


                } else if (null != mToastView) {
                    params.width = WindowManager.LayoutParams.MATCH_PARENT;
                    params.y = Constans.TOAST_VIEW_BOTTOM;
                } else {
                    params.width = WindowManager.LayoutParams.WRAP_CONTENT;
                }
                params.height = WindowManager.LayoutParams.WRAP_CONTENT;


                //隐私协议的弹窗
                if (null != mAgreementView) {
                    //距离屏幕顶部的距离
                    params.y = 155;
                    params.width = Constans.AGREEMENT_WIDTH;
                    params.height = Constans.AGREEMENT_HEIGHT;
                }

                if (null != mToastView) {
                    params.gravity = Gravity.BOTTOM | Gravity.CENTER;
                } else {
                    params.gravity = Gravity.TOP | Gravity.CENTER;
                }
                if (null == mToastView) {
                    params.windowAnimations = R.style.myPopup;
                }
                params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                        | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
                if (curCallView != null && !isRescue) {
                    curCallView.setWindowParams(params);
                }
            }
        }
        return params;
    }


    /**
     * ToastView
     *
     * @param context
     */
    public static void showToastPopView(Context context) {

        if (mToastView != null) return;
        if (mWindowManager == null) {
            mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        mToastView = LayoutInflater.from(context).inflate(R.layout.toast_view, null);

        mWindowManager.addView(mToastView, initParam(context, Call.CALL_TYPE_ECALL, false, false));
        RxUtils.delayDo(5, TimeUnit.SECONDS, (result, data) -> {
            if (mToastView != null) {
                mWindowManager.removeView(mToastView);
                mToastView = null;
            }
        });
    }

    private static Disposable disposable;

    /**
     * ETA倒计时结束弹框
     */
    public static void showSosArrivePopView(final Context context) {

        if (mArrivedView != null) return;
        if (mWindowManager == null) {
            mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        mArrivedView = LayoutInflater.from(context).inflate(R.layout.rescue_arrived_layout, null);

        if (null != mArrivedView && null != mWindowManager) {

            TextView tvOther = mArrivedView.findViewById(R.id.other_tv);
            TextView btOk = mArrivedView.findViewById(R.id.btn_ok);
            if (null != tvOther) {
                tvOther.setText(MyApplication.sApp.getText(R.string.rescue_arrived));
            }

            //5S之后
            disposable = RxUtils.delayDo(Constans.DISMISS_ETA_TIME_DELAY, TimeUnit.MILLISECONDS, (result, data) -> {
                if (mArrivedView != null) {
                    mWindowManager.removeView(mArrivedView);
                    mArrivedView = null;
                    disposable = null;
                }
            });
            if (null != btOk) {
                btOk.setOnClickListener((v) -> {
                    if (mArrivedView != null && disposable != null) {
                        mWindowManager.removeView(mArrivedView);
                        disposable.dispose();
                        disposable = null;
                        mArrivedView = null;

                    }
                });
            }
            mWindowManager.addView(mArrivedView, initParam(context, Call.CALL_TYPE_ECALL, true, false));

        }
    }

    /**
     * 显示ETA倒计时window
     */
    public static void showRescueWindow(final Context context, final int callType, final int time) {
        if (RescueViewHelper.getSingleton().getView() != null) {
            RescueViewHelper.getSingleton().getView().updateTime(time);
            return;
        }

        //当处于通话状态时，上方留出来给倒计时界面，将通话窗口下移
        setViewTopMargins(curCallView, true);

//        if (mRescueView == null) {
//            mRescueView = new RescueView(context);
        mRescueView = RescueViewHelper.getSingleton().getRescueView(context);
        if (mWindowManager == null) {
            mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        WindowManager.LayoutParams params = initParam(context, callType, false, true);
        params.flags = WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
        params.windowAnimations = 0;
        // params.y = 64; KX11与HX11救援窗口离顶部距离不同，需要额外处理
        mWindowManager.addView(mRescueView, params);
        mRescueView.updateTime(time);
//        } else {
//            LogHelper.d(TAG, "showRescueWindow error");
//        }
    }

    /**
     * 关闭ETA倒计时，并弹出SosArrive提示
     *
     * @param context
     * @param needShowArrive
     */
    public static void dismissRescueWindow(Context context, boolean needShowArrive) {
        if (mRescueView != null) {
            mWindowManager.removeView(mRescueView);
            mRescueView = null;
            RescueViewHelper.getSingleton().setViewNull();
            if (needShowArrive) {
                showSosArrivePopView(context);
            }
            // ETA倒计时关闭后将通话窗口上移
            setViewTopMargins(curCallView, false);
        }
    }


    public static void hideCallWindowDelay(int delayTime) {
        RxUtils.delayDo(delayTime, TimeUnit.MILLISECONDS, (result, data) -> hideCallWindow());
    }

    public static ViewType getCallWindowType() {
        return mViewType;
    }

    public static boolean isRescueWindowShow() {
        return RescueViewHelper.getSingleton().getView() != null;
    }

    /**
     * 处理 救援到达时间窗口 和 通话中窗口(缩小化，极小化)同时出现的场景:
     * 1. 挂断电话后，重新拨打电话
     * 2. 挂断电话后，收到服务中心来电
     * 通话中窗口需要下移，给救援到达时间窗口预留显示位置
     */
    public static void setViewTopMargins(BaseCallView view, boolean isRescueShow) {
        if (view == null || mViewParams == null) {
            return;
        }
        view.setWindowOffset(mViewParams, isRescueShow);
    }

}
